<template>
  <div class="login" :style="{ backgroundImage: `url('${loginBg}')`, backgroundSize: 'cover' }">
    <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" :style="loginStyle">
      <h3 class="title">{{ title }}</h3>
      <div v-if="loginType == 'username'">
        <el-form-item prop="username">
          <el-input v-model="loginForm.username" type="text" auto-complete="off" placeholder="账号">
            <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="loginForm.password" type="password" auto-complete="off" placeholder="密码"
            @keyup.enter.native="handleLogin">
            <svg-icon slot="prefix" icon-class="password" class="el-input__icon input-icon" />
          </el-input>
        </el-form-item>
        <el-form-item prop="code" v-if="captchaEnabled">
          <el-input v-model="loginForm.code" auto-complete="off" placeholder="验证码" style="width: 63%"
            @keyup.enter.native="handleLogin">
            <svg-icon slot="prefix" icon-class="validCode" class="el-input__icon input-icon" />
          </el-input>
          <div class="login-code">
            <img :src="codeUrl" @click="getCode" class="login-code-img" />
          </div>
        </el-form-item>
        <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 25px 0px;">记住密码</el-checkbox>
        <el-form-item style="width:100%;">
          <el-button :loading="loading" size="medium" type="primary" style="width:100%;"
            @click.native.prevent="handleLogin">
            <span v-if="!loading">登 录</span>
            <span v-else>登 录 中...</span>
          </el-button>
          <div style="float: right;" v-if="register">
            <router-link class="link-type" :to="'/register'">立即注册</router-link>
          </div>
        </el-form-item>
      </div>
      <div v-if="loginType == 'wechat'">
        <QrCode :url="qrUrl" title="微信扫码登录" :isDown="false" :isEdit="false" @edit="" />
      </div>
      <div class="login-tip">
        其他登录方式：
      </div>
      <div class="login-btn-grop">
        <img v-if="loginType != 'username'" src="@/assets/logo/logo.png" class="loginTypeBtn"
          @click="upType('username')">
        <img v-if="loginType != 'wechat'" src="@/assets/images/wx.png" class="loginTypeBtn" @click="upType('wechat')">

      </div>
    </el-form>

    <!--  底部  -->
    <div class="el-login-footer">
      <!-- <span>Copyright © 2018-2025 ruoyi.vip All Rights Reserved.</span> -->
    </div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import { setToken } from '@/utils/auth'
import { mapActions } from 'vuex';


import { getCodeImg, getTenantByKey } from "@/api/login";
import Cookies from "js-cookie";
import { encrypt, decrypt } from '@/utils/jsencrypt'
import QrCode from "./components/QrCode.vue";

import { getWxLoginTemp, checkWxLoginStatus } from "@/api/wechat";
import { getConfigKey } from '@/api/system/config'

import { getPlatformConfigByPath, getPlatformConfigByRole } from '@/router/platform'


export default {
  name: "Login",
  components: { QrCode },
  ...mapActions('permission', ['GenerateRoutes']),
  computed: {
  },
  data() {
    return {

      title: process.env.VUE_APP_TITLE,// VUE_APP_TITLE

      codeUrl: "",
      loginForm: {
        username: "",
        password: "",
        rememberMe: false,
        code: "",
        uuid: ""
      },
      loginRules: {
        username: [
          { required: true, trigger: "blur", message: "请输入您的账号" }
        ],
        password: [
          { required: true, trigger: "blur", message: "请输入您的密码" }
        ],
        code: [{ required: true, trigger: "change", message: "请输入验证码" }]
      },
      loading: false,
      // 租户列表
      tenantList: [],
      // 验证码开关
      captchaEnabled: false,
      // 注册开关
      register: false,
      redirect: undefined,

      // 微信登录二维码链接
      qrUrl: '',
      loginType: "username", // username/wechat
      tempToken: '',
      loginBg: require('@/assets/images/login-background.jpg'),
      loginStyle: '',
      baseApi: process.env.VUE_APP_BASE_API,
      platC: {},

    };
  },
  watch: {
    $route: {
      handler: function (route) {
        this.redirect = route.query && route.query.redirect;
      },
      immediate: true,
    }
  },
  created() {
    this.init()
    this.getUrlKey()
    // this.getCode();
    this.getCookie();

    // 根据路由获取平台信息
    this.platC = getPlatformConfigByPath(this.$route.path)
    console.log(this.platC)
  },
  methods: {
    getUrlKey() {
      const key = this.$route.query.key
      if (key) {
        console.log("lastTenantKey", key, Cookies.get("lastTenantKey"))

        if (Cookies.get("lastTenantKey") != key) {
          getTenantByKey(key).then(res => {
            console.log("getTenantByKey", res)
            Cookies.set("lastTenantId", res.data.tenantId.toString(), { expires: 30 });
            Cookies.set("lastTenantKey", res.data.tenantKey.toString(), { expires: 30 });
          })
        }
      } else {
        this.$message.warning("登录链接错误！请使用正确的链接打开该页面！")
      }
    },
    upType(type) {
      this.loginType = type;
      if (type == "username") {
        clearInterval(this.setTimer)
      } else {
        this.setTimer = setInterval(() => {
          this.setOpenLocal()
        }, 2000)
      }
    },
    getCode() {
      getCodeImg().then(res => {
        this.captchaEnabled = res.captchaEnabled === undefined ? true : res.captchaEnabled;
        if (this.captchaEnabled) {
          this.codeUrl = "data:image/gif;base64," + res.img;
          this.loginForm.uuid = res.uuid;
        }
      });
    },
    init() {
      getConfigKey('sys.index.loginBg').then(response => {
        if (response.msg && response.msg.length > 10) {
          this.loginBg = this.baseApi + response.msg
        }
      });
      getConfigKey('sys.index.loginStyle').then(response => {
        if (response.msg) {
          this.loginStyle = response.msg
        }
      });
      getWxLoginTemp().then(res => {
        if (res.code == 200) {
          this.tempToken = res.tempToken  // tempToken
          this.getQrCode("&tempToken=" + this.tempToken)

        } else {
          this.$message.warning(res.msg)
        }
      })
    },
    setOpenLocal() {

      checkWxLoginStatus({ tempToken: this.tempToken }).then(res => {
        if (res && res.token) {
          clearInterval(this.setTimer)
          this.$store.dispatch("Login", this.loginForm).then(() => {
            this.$router.push({ path: this.redirect || "/adminHome" }).catch(() => { });
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
          // console.log("clearInterval", this.setTimer)
          // Cookies.set("token", res.token);
          // this.$store.getters.token = res.token
          // Cookies.set("token", this.$store.getters);
          // console.log("res.token", this.$store.getters, this.$store.getters.token)
          setToken(res.token);
          // 2. 同步到 Vuex
          // this['user/SET_TOKEN'](res.token);
          // 调用 user 模块的 GetInfo action
          this.$store.dispatch('GetInfo')
            .then(res => {
              // 成功回调：res 是接口返回的用户信息数据
              // console.log('用户信息获取成功', res);
              // 可以在这里处理获取到的用户信息（如渲染到页面）
              const userInfo = res.user; // 用户基本信息
              const roles = res.roles; // 角色信息
              const permissions = res.permissions; // 权限信息
            })
            .catch(error => {
              // 失败回调：如 token 失效、接口错误等
              console.error('用户信息获取失败', error);
              // 通常需要跳转登录页重新登录
              // this.$router.push('/login');
            });

          this.$store.dispatch('GenerateRoutes')
            .then(rewriteRoutes => {
              // 成功回调：rewriteRoutes 是生成的动态路由数组
              console.log('动态路由生成成功222', rewriteRoutes);
              // 路由生成后可执行跳转等操作（如跳转到首页）
              this.$router.push('/adminHome');
            })
            .catch(error => {
              // 失败回调：如接口请求失败
              console.error('动态路由生成失败', error);
            });



          setTimeout(() => {
            this.$router.push({ path: "/adminHome" })
          }, 10000)
          // const data = res.data
          // console.log(this.setTimer)
        } else if (res && res.code == 500) {
          // 超过时限，重新进入页面
          // this.$message.error("二维码已过期，请重新扫码")
          window.location.reload()
          return
        } else {

        }
      });
    },
    getQrCode(queryStr = "") {
      // console.log("getQrCode!!!!!：：this.$store.state.user", this.user)
      this.qrUrl = window.location.origin + '/wechat/getWxInfo?backPage=/wechat/backLogin' + queryStr
      // console.log("qrUrl", this.qrUrl);
    },
    getCookie() {
      const username = Cookies.get("username");
      const password = Cookies.get("password");
      const rememberMe = Cookies.get('rememberMe')
      const lastTenantId = Cookies.get("lastTenantId");
      this.loginForm = {
        tenantId: lastTenantId ? Number(lastTenantId) : "",
        username: username === undefined ? this.loginForm.username : username,
        password: password === undefined ? this.loginForm.password : decrypt(password),
        rememberMe: rememberMe === undefined ? false : Boolean(rememberMe)
      };
    },
    handleLogin() {
      this.$refs.loginForm.validate(valid => {
        if (valid) {
          this.loading = true;
          if (this.loginForm.rememberMe) {
            Cookies.set("username", this.loginForm.username, { expires: 30 });
            Cookies.set("password", encrypt(this.loginForm.password), { expires: 30 });
            Cookies.set('rememberMe', this.loginForm.rememberMe, { expires: 30 });
          } else {
            Cookies.remove("username");
            Cookies.remove("password");
            Cookies.remove('rememberMe');
          }
          const lastTenantId = Cookies.get("lastTenantId");
          console.log(lastTenantId)
          if (!lastTenantId) {
            this.$message.warning("登录链接错误！请使用正确的链接打开该页面！")
            return;
          }

          // === 修复：确保租户ID正确传递 ===
          const loginData = {
            username: this.loginForm.username,
            password: this.loginForm.password,
            rememberMe: this.loginForm.rememberMe,
            code: this.loginForm.code,
            uuid: this.loginForm.uuid,
            tenantId: lastTenantId // 明确传递租户ID
          };

          // console.log('登录请求数据:', loginData); // 调试日志

          this.$store.dispatch("Login", loginData).then(() => {
            this.$store.dispatch('GetInfo').then(() => {
              const roles = this.$store.getters.roles
              const userInfo = this.$store.getters.user
              // console.log('用户信息获取成功', userInfo);
              if (userInfo && userInfo.tenantId) {
                localStorage.setItem('userInfo', JSON.stringify(userInfo))
              }
              if (roles.length>0) {
                this.platC = getPlatformConfigByRole(roles[0])
                this.$router.push({ path: this.redirect || this.platC?.homePath }).catch(() => { })
              } else {

              }
            })
          }).catch(() => {
            this.loading = false;
            if (this.captchaEnabled) {
              this.getCode();
            }
          });
        }
      });
    }
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.login {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100%;

}

.title {
  margin: 0px auto 30px auto;
  text-align: center;
  color: #707070;
}

.login-form {
  border-radius: 6px;
  background: #ffffff;
  width: 400px;
  max-width: 90%;
  padding: 25px 25px 5px 25px;

  .el-input {
    height: 38px;

    input {
      height: 38px;
    }
  }

  .input-icon {
    height: 39px;
    width: 14px;
    margin-left: 2px;
  }
}

.login-tip {
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-code {
  width: 33%;
  height: 38px;
  float: right;

  img {
    cursor: pointer;
    vertical-align: middle;
  }
}

.el-login-footer {
  height: 40px;
  line-height: 40px;
  position: fixed;
  bottom: 0;
  width: 100%;
  text-align: center;
  color: #fff;
  font-family: Arial;
  font-size: 12px;
  letter-spacing: 1px;
}

.login-code-img {
  height: 38px;
}

.login-tip {
  padding-top: 10px;
  border-top: 1px solid #e5e5e5;
  font-size: 13px;
  text-align: center;
  color: #bfbfbf;
}

.login-btn-grop {
  width: 90%;
  margin: 10px auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-btn-grop img {
  width: 30px;
  height: 30px;
  margin: 0 10px;
  cursor: pointer;
}
</style>
